#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <../../resource/include/extractGraph/extractgraph.h>
#include <../../resource/include/multipleImage/multipleImage.h>

using namespace std;
using namespace cv;

int main()
{
    ExtractGraph extractImg;
    Mat img1 = extractImg.extractComponet(imread("../../resource/image/base/NPN.jpg"));
    Mat img2 = extractImg.extractComponet(imread("../../resource/image/circult/image1.jpg"));
    imshow("img1", img1);
    imshow("img2", img2);
    //////////////ORB检测//////////////////
    vector<KeyPoint> keyPoint1, keyPoint2;
    Mat descriptor1, descriptor2;
    Ptr<ORB> orb = ORB::create();
    //检测Oriented FAST角点位置
    orb->detect(img1, keyPoint1);
    orb->detect(img2, keyPoint2);
    //根据角点位置计算BRIEF描述子
    orb->compute(img1, keyPoint1, descriptor1);
    orb->compute(img2, keyPoint2, descriptor2);
    //定义输出检测特征点的图片
    Mat outImg1;
    drawKeypoints(img1, keyPoint1, outImg1, Scalar::all(-1), DrawMatchesFlags::DEFAULT);
    imshow("ORB特征点", outImg1);
    //对两幅图图像中的BRIEFF描述子进行匹配，使用Hamming距离
    vector<DMatch> matches;
    BFMatcher matcher(NORM_HAMMING);
    matcher.match(descriptor1, descriptor2, matches);
    //遍历matches[]数组, 找出匹配点的最大距离和最小距离
    double minDist = 0, maxDist = 0;
    for (int i=0; i<descriptor1.rows; ++i)
    {
        double dist = matches[i].distance;
        if (dist < minDist) minDist = dist;
        if (dist > maxDist) maxDist = dist;
    }
    cout << "Max dist: " << maxDist;
    cout << "Min dist: " << minDist;
    //根据最小距离，对匹配点进行筛选
    vector<DMatch> goodMatches;
    for (auto a : matches)
        cout << a.distance << endl;
    for (int j=0; j<descriptor1.rows; ++j)
    {
//        if (matches[j].distance <= max(2*minDist, 30.0))
//            goodMatches.push_back(matches[j]);
        if (matches[j].distance <= 2*minDist)
            goodMatches.push_back(matches[j]);
    }
    //绘制结果
    Mat imgMatch;
    drawMatches(img1, keyPoint1, img2, keyPoint2, matches, imgMatch);
    imshow("所有匹配点对", imgMatch);

    Mat imgGoodMatch;
    drawMatches(img1, keyPoint1, img2, keyPoint2, goodMatches, imgGoodMatch);
    imshow("筛选后的匹配点对", imgGoodMatch);

    waitKey(0);
    destroyAllWindows();
    return 0;
}
